var express = require('express')
var router = express.Router()

// 引入医美模块的医院模型
const { hospitalModel } = require('../db/models/cosmetic')

// 获取医院（机构）列表 - 支持按名称、状态（基于服务关联数组）、城市、省份、分类筛选，支持分页和排序
router.get('/hospitals', async (req, res) => {
  try {
    const {
      name,           // 机构名称（模糊）
      status,         // active/inactive -> 基于服务关联数组判断
      city,
      province,
      category,       // 医院分类
      sortBy = 'createTime',  // 排序字段：rating, createTime, viewCount
      sortOrder = 'desc',     // 排序方向：asc, desc
      page = 1,
      limit = 10,
    } = req.query

    const query = {}

    if (name && name.trim()) {
      query.name = { $regex: name.trim(), $options: 'i' }
    }

    // 基于status字段筛选状态
    if (status === 'active') query.status = 'active'      // 启用状态
    if (status === 'inactive') query.status = 'inactive'  // 禁用状态

    if (city && city.trim()) query.city = city.trim()
    if (province && province.trim()) query.province = province.trim()
    if (category && category.trim()) query.category = category.trim()

    const pageNum = parseInt(page) || 1
    const limitNum = parseInt(limit) || 10
    const skip = (pageNum - 1) * limitNum

    // 构建排序对象
    const sortObj = {}
    const validSortFields = ['rating', 'createTime', 'viewCount']
    const sortField = validSortFields.includes(sortBy) ? sortBy : 'createTime'
    const sortDirection = sortOrder === 'asc' ? 1 : -1
    sortObj[sortField] = sortDirection
    
    // 如果不是按浏览量排序，添加浏览量作为次要排序
    if (sortField !== 'viewCount') {
      sortObj.viewCount = -1
    }

    const [items, total] = await Promise.all([
      hospitalModel
        .find(query)
        .sort(sortObj)
        .skip(skip)
        .limit(limitNum),
      hospitalModel.countDocuments(query),
    ])

    // 适配前端 Organization.vue 期待的字段
    const data = items.map((h) => {
      const mappedData = {
        id: h._id,
        image: h.logo ? (h.logo.startsWith('http') ? h.logo : `${req.protocol}://${req.get('host')}${h.logo}`) : '',
        name: h.name,
        address: h.location || `${h.province || ''}${h.city || ''}`,
        category: h.category || '-',
        rating: h.rating || 0,
        status: h.status || 'inactive', // 直接使用数据库中的状态字段
        createTime: h.createTime,
        // 附带原始字段，方便后续扩展
        city: h.city,
        province: h.province,
        tag: h.tag,
        location: h.location,
        viewCount: h.viewCount,
        service: h.service,
        review: h.review,
        doctor: h.doctor
      }
      
      return mappedData
    })

    res.send({
      success: true,
      data,
      pagination: {
        page: pageNum,
        limit: limitNum,
        total,
        pages: Math.ceil(total / limitNum),
      },
    })
  } catch (error) {
    console.error('获取医院列表失败:', error)
    res.status(500).send({
      success: false,
      message: '获取医院列表失败',
      error: error.message,
    })
  }
})

// 创建新医院（机构）
router.post('/hospitals', async (req, res) => {
  try {
    const {
      name,
      logo,
      rating = 5.0,
      service = [],
      review = [],
      doctor = [],
      location,
      city,
      province,
      tag,
      category,
      status = 'inactive'
    } = req.body

    // 验证必填字段
    if (!name || !name.trim()) {
      return res.status(400).send({
        success: false,
        message: '机构名称不能为空'
      })
    }

    // 创建新医院记录
    const newHospital = new hospitalModel({
      name: name.trim(),
      logo: logo || '',
      rating: Number(rating) || 5.0,
      location: location || '',
      city: city || '',
      province: province || '',
      tag: tag || '',
      category: category || '',
      status: status || 'inactive',
      viewCount: 0,
      products: [], // 初始化为空数组（产品ID数组）
      // createTime 由数据库模型的默认值自动设置
      // 关联字段
      service: service || [],
      review: review || [],
      doctor: doctor || []
    })

    const savedHospital = await newHospital.save()

    res.send({
      success: true,
      message: '机构创建成功',
      data: {
        id: savedHospital._id,
        name: savedHospital.name,
        image: savedHospital.logo ? (savedHospital.logo.startsWith('http') ? savedHospital.logo : `${req.protocol}://${req.get('host')}${savedHospital.logo}`) : '', // 统一使用image字段名并处理完整URL
        logo: savedHospital.logo,
        rating: savedHospital.rating,
        location: savedHospital.location,
        city: savedHospital.city,
        province: savedHospital.province,
        tag: savedHospital.tag,
        category: savedHospital.category,
        status: savedHospital.status,
        viewCount: savedHospital.viewCount,
        createTime: savedHospital.createTime,
        service: savedHospital.service,
        review: savedHospital.review,
        doctor: savedHospital.doctor
      }
    })
  } catch (error) {
    console.error('创建医院失败:', error)
    
    // 处理重复名称错误
    if (error.code === 11000) {
      return res.status(400).send({
        success: false,
        message: '机构名称已存在，请使用其他名称'
      })
    }
    
    res.status(500).send({
      success: false,
      message: '创建医院失败',
      error: error.message
    })
  }
})

// 批量更新医院状态（必须在参数化路由之前定义，避免路由匹配冲突）
router.put('/hospitals/batch-status', async (req, res) => {
  try {
    console.log('=== 批量状态更新API调试信息 ===')
    console.log('请求体:', req.body)
    console.log('Content-Type:', req.headers['content-type'])
    
    const { ids, status } = req.body;
    
    console.log('解析后的参数:')
    console.log('- ids:', ids)
    console.log('- ids类型:', typeof ids)
    console.log('- ids是否为数组:', Array.isArray(ids))
    console.log('- ids长度:', ids?.length)
    console.log('- status:', status)
    console.log('- status类型:', typeof status)
    
    if (!ids || !Array.isArray(ids) || ids.length === 0) {
      console.log('❌ ID验证失败: 无效的ID列表')
      return res.status(400).send({
        success: false,
        message: '请提供要更新的医院ID列表'
      });
    }
    
    if (!status || !['active', 'inactive'].includes(status)) {
      console.log('❌ 状态验证失败: 无效的状态值')
      return res.status(400).send({
        success: false,
        message: '请提供有效的状态值（active 或 inactive）'
      });
    }
    
    // 验证ID格式
    const mongoose = require('mongoose');
    console.log('开始验证ID格式:')
    for (let i = 0; i < ids.length; i++) {
      const id = ids[i];
      const isValid = mongoose.Types.ObjectId.isValid(id);
      console.log(`- ID[${i}]: "${id}" (类型: ${typeof id}, 长度: ${id?.length}, 有效: ${isValid})`)
      if (!isValid) {
        console.log(`❌ ID格式验证失败: ${id}`)
        return res.status(400).send({
          success: false,
          message: `无效的医院ID格式: ${id} (类型: ${typeof id})`
        });
      }
    }
    console.log('✅ 所有ID格式验证通过')
    
    // 批量更新状态
    console.log('执行数据库更新操作...')
    const result = await hospitalModel.updateMany(
      { _id: { $in: ids } },
      { $set: { status: status } }
    );
    
    console.log('数据库更新结果:', result)
    console.log(`✅ 批量更新了 ${result.modifiedCount} 个医院的状态为 ${status}`);
    
    const responseData = {
      success: true,
      message: `成功${status === 'active' ? '启用' : '禁用'} ${result.modifiedCount} 个医院`,
      updatedCount: result.modifiedCount
    };
    
    console.log('返回响应数据:', responseData)
    res.send(responseData);
  } catch (error) {
    console.error('=== 批量更新异常详情 ===')
    console.error('错误类型:', error.constructor.name)
    console.error('错误消息:', error.message)
    console.error('错误堆栈:', error.stack)
    console.error('完整错误对象:', error)
    
    res.status(500).send({
      success: false,
      message: '批量更新医院状态失败',
      error: error.message
    });
  }
});

// 更新医院（机构）
router.put('/hospitals/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const updateData = req.body;
    
    // 验证ID格式
    const mongoose = require('mongoose');
    if (!mongoose.Types.ObjectId.isValid(id)) {
      return res.status(400).send({
        success: false,
        message: '无效的医院ID格式'
      });
    }
    
    // 移除不应该被更新的字段
    delete updateData._id;
    delete updateData.__v;
    
    // 更新医院信息
    const hospital = await hospitalModel.findByIdAndUpdate(
      id,
      updateData,
      { new: true, runValidators: true }
    );
    
    if (!hospital) {
      return res.status(404).send({
        success: false,
        message: '医院不存在'
      });
    }
    
    res.send({
      success: true,
      message: '医院更新成功',
      data: hospital
    });
  } catch (error) {
    console.error('更新医院失败:', error);
    res.status(500).send({
      success: false,
      message: '更新医院失败',
      error: error.message
    });
  }
});

// 批量删除医院（必须在单个删除之前，避免路由匹配冲突）
router.delete('/hospitals/batch', async (req, res) => {
  try {
    const { ids } = req.body;
    
    if (!ids || !Array.isArray(ids) || ids.length === 0) {
      return res.status(400).send({
        success: false,
        message: '请提供要删除的医院ID列表'
      });
    }
    
    // 验证ID格式
    const mongoose = require('mongoose');
    for (const id of ids) {
      if (!mongoose.Types.ObjectId.isValid(id)) {
        return res.status(400).send({
          success: false,
          message: `无效的医院ID格式: ${id}`
        });
      }
    }
    
    // 先获取要删除的医院信息，用于清理产品关联
    const hospitals = await hospitalModel.find({ _id: { $in: ids } });
    
    // 删除医院
    const result = await hospitalModel.deleteMany({ _id: { $in: ids } });
    
    // 清理产品中的医院关联
    const { productModel } = require('../db/models/cosmetic');
    for (const hospital of hospitals) {
      if (hospital.products && hospital.products.length > 0) {
        await productModel.updateMany(
          { 'hospitals.hospitalId': hospital._id },
          { $pull: { hospitals: { hospitalId: hospital._id } } }
        );
      }
    }
    
    console.log(`批量删除了 ${result.deletedCount} 个医院，并清理了相关产品的关联`);
    
    res.send({
      success: true,
      message: `成功删除 ${result.deletedCount} 个医院`,
      deletedCount: result.deletedCount
    });
  } catch (error) {
    console.error('批量删除医院失败:', error);
    res.status(500).send({
      success: false,
      message: '批量删除医院失败',
      error: error.message
    });
  }
});

// 删除单个医院
router.delete('/hospitals/:id', async (req, res) => {
  try {
    const { id } = req.params;
    
    // 验证ID格式
    const mongoose = require('mongoose');
    if (!mongoose.Types.ObjectId.isValid(id)) {
      return res.status(400).send({
        success: false,
        message: '无效的医院ID格式'
      });
    }
    
    // 先获取医院信息，用于清理产品关联
    const hospital = await hospitalModel.findById(id);
    if (!hospital) {
      return res.status(404).send({
        success: false,
        message: '医院不存在'
      });
    }
    
    // 删除医院
    const result = await hospitalModel.findByIdAndDelete(id);
    
    // 如果医院有关联的产品，需要清理产品中的医院关联
    if (hospital.products && hospital.products.length > 0) {
      const { productModel } = require('../db/models/cosmetic');
      
      // 从相关产品的hospitals字段中移除该医院ID
      await productModel.updateMany(
        { 'hospitals.hospitalId': hospital._id },
        { $pull: { hospitals: { hospitalId: hospital._id } } }
      );
      
      console.log(`已从 ${hospital.products.length} 个产品中移除已删除医院 ${hospital._id} 的关联`);
    }
    
    res.send({
      success: true,
      message: '医院删除成功'
    });
  } catch (error) {
    console.error('删除医院失败:', error);
    res.status(500).send({
      success: false,
      message: '删除医院失败',
      error: error.message
    });
  }
});

module.exports = router


